<?php

// [ 短信码 ]
// use app\common\lib\SmsCode as SmsCodeCommonLib;
// $mobile = ;
// $alias  = ;
// $code   = ;
// $bool = SmsCodeCommonLib::write($mobile,$alias,$code);
// if ($bool) {
//     $msg = '短信码发送成功';
// } else {
//     $msg = '2次发送间隔必须大于60秒';
// }
// 
// $res = SmsCodeCommonLib::check($mobile,$alias,$code);
// if ('not_found'  == $res) return [400,'未发送短信码'];
// if ('code_error' == $res) return [400,'短信码不正确'];
// if ('success' == $res) {
// 
// }

namespace app\common\lib;
use think\Db;

class SmsCode
{
    public static function write($mobile, $alias, $code)
    {
        $bool = self::_validate($mobile,$alias);

        // 2次发送间隔必须大于60秒
        if (!$bool) return false;

        $data['mobile']      = $mobile;
        $data['alias']       = $alias;
        $data['code']        = $code;
        $data['create_time'] = time();
        $num = Db::name('sms')->insert($data);

        return ($num > 0) ? true : false;
    }

    public static function check($mobile, $alias, $code)
    {
        $where['mobile'] = $mobile;
        $where['alias']  = $alias;
        $ret = Db::name('sms')->where($where)->order('create_time DESC')->find();
        if ( is_null($ret) ) {
            return 'not_found';
        } else {
            if ($ret['code'] == $code) {
                // 删除记录
                Db::name('sms')->where($where)->delete();
                return 'success';
            } else {
                return 'code_error';
            }
        }
    }

    // --------------------------------------------------
    
    private static function _validate($mobile, $alias)
    {
        $where['mobile'] = $mobile;
        $where['alias']  = $alias;
        $ret = Db::name('sms')->where($where)->find();
        if ( !is_null($ret) ) {
            if ( ( time() - $ret['create_time'] ) > 60 ) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }
}